package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.cyys.common.thirdInterface.aliyun.OssUtil;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BinaryUploader {
//
//	@Value("${cyys.file.rootPath}")
//	private static String physicalPath;

	public static final State save(HttpServletRequest request,
			Map<String, Object> conf) {
		boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;

		//=(Boolean)conf.get("ossUpload");

	    if (!ServletFileUpload.isMultipartContent(request)) {  
	        return new BaseState(false, 5);  
	    }  
	    ServletFileUpload upload = new ServletFileUpload(  
	            new DiskFileItemFactory());  
	    if (isAjaxUpload) {  
	        upload.setHeaderEncoding("UTF-8");  
	    }  
	    try {  
	        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
	           MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());  
	  
	           String savePath = (String) conf.get("savePath");  
	           String originFileName = multipartFile.getOriginalFilename();  
	           String suffix = FileType.getSuffixByFilename(originFileName);  
	  
	           originFileName = originFileName.substring(0,originFileName.length() - suffix.length());  
	           savePath = savePath + suffix;  
	  
	           long maxSize = ((Long) conf.get("maxSize")).longValue();

				int uploadMode = ((Integer) conf.get("uploadMode")).intValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
	               return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);  
	           }  
	           /***********/  
	           //自定义  
	           savePath = PathFormat.parse(savePath, originFileName);

	           String physicalPath = (String) conf.get("saveRootPath");

	           String fileName = savePath.substring(savePath.lastIndexOf("/") + 1, savePath.length());
	           State storageState;
	           String pathTemp = physicalPath + savePath.substring(0,savePath.lastIndexOf("/"));

				//若编辑器开启OSS上传走OSS上传方式
				switch (uploadMode){
					case 1:{
						Boolean uploadeResult=OssUtil.upLoadFile(multipartFile.getInputStream(),savePath.substring(1,savePath.length()));
						//将OSS上传结果返回
						if(uploadeResult){
							storageState=new BaseState(true);
						}else{
							storageState=new BaseState(false, AppInfo.IO_ERROR);
						}
					}break;
					case 2:{
						File targetFile = new File(pathTemp);
						if(!targetFile.exists()){
							targetFile.mkdirs();
						}
						storageState = StorageManager.saveFileByInputStream(multipartFile.getInputStream(),pathTemp+"/"+fileName, maxSize);
					}break;
					default:{
						Boolean uploadeResult=OssUtil.upLoadFile(multipartFile.getInputStream(), savePath.substring(1,savePath.length()));
						//将OSS上传结果返回
						if(uploadeResult){
							storageState=new BaseState(true);
						}else{
							storageState=new BaseState(false, AppInfo.IO_ERROR);
						}
					}

				}


	           //System.out.println(new File(pathTemp).exists());  
	           /************/  
	           //State storageState = StorageManager.saveFileByInputStream(multipartFile.getInputStream(),savePath, maxSize);


	         //  new OssUtil();
	          // OssUtil.upLoadFile(multipartFile.getInputStream(),pathTemp+"/"+fileName);
	           if (storageState.isSuccess()) {
				   storageState.putInfo("url",PathFormat.format(savePath));
	               storageState.putInfo("type", suffix);  
	               storageState.putInfo("original", originFileName + suffix);  
	           }  
	  
	           return storageState;  
	  
	       }catch (Exception e) {  
	           e.printStackTrace();  
	           System.out.println(e.getMessage());  
	       }  
	       return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
